package ude.univ.esiag.gon.uchiha.register;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Properties;

import javax.rmi.PortableRemoteObject;

import org.omg.CORBA.ORB;
import org.omg.CORBA.Object;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.POAHelper;

import ude.univ.esiag.gon.uchiha.subscriber.Subscriber;
import ude.univ.esiag.gon.uchiha.subscriber.impl.SubscriberImpl;
import ude.univ.esiag.gon.uchiha.subscriber.impl._SubscriberImpl_Tie;

public class MulticasterClient {
	private static MulticasterClient singleton;
	private ORB orb;
	private POA rootPOA;
	private MulticasterClient(){
		Properties pro = new Properties();
		String host = getHost();
		
		pro.put("com.sun.CORBA.ORBServerHost", host);
		
		orb = ORB.init(new String[]{}, pro);
		
		try{
			rootPOA = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
			rootPOA.the_POAManager().activate();
		}catch(Exception e){
			e.printStackTrace();
		}
		new Thread(new Runnable() {
			
			public void run() {
				orb.run();
			}
		}).start();
	}
	public String getHost(){
		try{
			String interfaceS = "wlan0";
			NetworkInterface inter = NetworkInterface.getByName(interfaceS);
			Enumeration<InetAddress> adres = inter.getInetAddresses();
			String x = "";
			while(adres.hasMoreElements()){
				x = adres.nextElement().getHostAddress();
			}
			return x;
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	public static MulticasterClient getInstance(){
		if(singleton == null)
			singleton = new MulticasterClient();
		return singleton;
	}
	public Subscriber ior_to_subscriber(String ior){
		Object objRef = orb.string_to_object(ior);
		return (Subscriber)PortableRemoteObject.narrow(objRef, Subscriber.class);
	}
	public String subscriber_to_ior(SubscriberImpl subscriber){
		String ior = null;
		_SubscriberImpl_Tie tie = new _SubscriberImpl_Tie();
		tie.setTarget(subscriber);
		try{
			Object objRef = rootPOA.servant_to_reference(tie);
			ior = orb.object_to_string(objRef);
		}catch(Exception e){
			e.printStackTrace();
		}
		return ior;
	}
	public void broadcast(String name, String ior){
		try{
			byte[] buf =(name + "/" + ior).getBytes();
			InetAddress address = InetAddress.getByName("228.5.6.7");
			DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 9092);
			DatagramSocket socket = new DatagramSocket();
			socket.send(packet);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
